/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry;

import io.sentry.util.Objects;

import java.io.Closeable;
import java.io.IOException;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.annotations.VisibleForTesting;

/**
 * Registers hook that closes {@link Hub} when main thread shuts down.
 *
 * @since 2021-06-02
 **/
public final class ShutdownHookIntegration implements Integration, Closeable {
    private final @NotNull Runtime runtime;
    private @Nullable Thread thread;

    /**
     * constructor
     */
    public ShutdownHookIntegration() {
        this(Runtime.getRuntime());
    }

    /**
     * constructor
     *
     * @param runtime Runtime
     */
    @TestOnly
    public ShutdownHookIntegration(final @NotNull Runtime runtime) {
        this.runtime = Objects.requireNonNull(runtime, "Runtime is required");
    }

    @Override
    public void register(final @NotNull IHub hub, final @NotNull SentryOptions options) {
        Objects.requireNonNull(hub, "Hub is required");

        thread = new Thread(() -> hub.close());
        runtime.addShutdownHook(thread);
    }

    @Override
    public void close() throws IOException {
        if (thread != null) {
            runtime.removeShutdownHook(thread);
        }
    }

    @VisibleForTesting
    @Nullable
    Thread getHook() {
        return thread;
    }
}
